package com.qingcheng.consumer;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.qingcheng.dao.SeckillGoodsMapper;
import com.qingcheng.dao.SeckillOrderMapper;
import com.qingcheng.pojo.seckill.SeckillGoods;
import com.qingcheng.pojo.seckill.SeckillOrder;
import com.qingcheng.pojo.seckill.SeckillStatus;
import com.qingcheng.service.order.WeixinPayService;
import com.qingcheng.util.DateUtil;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;

public class SeckillOrderTimeoutConsumer implements MessageListener {

    @Override
    public void onMessage(Message message) {
        String content = new String(message.getBody());
        System.out.println("接收到消息");
        rollBackOrder(JSON.parseObject(content,SeckillStatus.class));
    }

    @Autowired
    private RedisTemplate redisTemplate;

    @Reference
    private WeixinPayService weixinPayService;
    
    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Autowired
    private SeckillOrderMapper seckillOrderMapper;


    /**
     * 订单处理以及回滚库存处理
     *
     * @param seckillStatus
     */
    public void rollBackOrder(SeckillStatus seckillStatus) {

        //获取redis中的订单信息
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.boundHashOps("SeckillOrder").get(seckillStatus.getUsername());

        //如果redis中有订单信息，说明用户未支付 或者调用微信支付查询订单接口（已经写过了）来查询订单是否支付
        if (seckillOrder == null) {
            return;
        }
        //关闭支付
        Map<String, String> mapResult = weixinPayService.closeOrder(seckillStatus.getOrderId().toString());

        if(mapResult==null){
            throw new RuntimeException("关闭失败");
        }else {
            if("SUCCESS".equals(mapResult.get("return_code"))){
                if("SUCCESS".equals(mapResult.get("result_code"))){ //查询交易状态是否为SUCCESS
//                    System.out.println("关闭成功");
                }
            }else{
                throw new RuntimeException(mapResult.get("err_code_des"));//返回错误描述
            }
        }

        //删除订单
        redisTemplate.boundHashOps("SeckillOrder").delete(seckillStatus.getUsername());

        //回滚库存
        //1)从Redis中获取该商品
        SeckillGoods seckillGoods = (SeckillGoods) redisTemplate.boundHashOps("SeckillGoods_"+ seckillStatus.getTime()).get(seckillStatus.getGoodsId());
        //2)如果Redis中没有，则从数据库中加载
        if(seckillGoods==null){
            seckillGoods = seckillGoodsMapper.selectByPrimaryKey(seckillStatus.getGoodsId());
        }
        //3)数量+1 (递增数量+1，队列数量+1)
        Long surplusCount = redisTemplate.boundHashOps("SeckillGoodsCount" + seckillStatus.getTime()).increment(seckillStatus.getGoodsId(), 1);

        seckillGoods.setStockCount(surplusCount.intValue());

        redisTemplate.boundListOps("SeckillGoodsCountList_"+seckillStatus.getTime()+"_"+seckillStatus.getGoodsId()).leftPush(seckillStatus.getGoodsId());

        //数据同步到redis中
        redisTemplate.boundHashOps("SeckillGoods_"+seckillStatus.getTime()).put(seckillStatus.getGoodsId(),seckillGoods);

        //同步到mysql 商品的库存加1
        seckillGoodsMapper.updateByPrimaryKey(seckillGoods);

        //清理排队标识
        redisTemplate.boundHashOps("UserQueueCount").delete(seckillStatus.getUsername());

        //清理抢单标识
        redisTemplate.boundHashOps("UserQueueStatus").delete(seckillStatus.getUsername());


    }

}
